package com.bawei.module_mall.manager

import com.bawei.module_mall.model.Order
import java.util.*

object OrderManager {
    
    private val orders = mutableListOf<Order>()
    
    /**
     * 创建新订单
     */
    fun createOrder(
        sellerName: String,
        productTitle: String,
        productPrice: String,
        quantity: Int,
        tag1: String = "",
        tag2: String = "",
        productImageUrl: String? = null
    ): Order {
        val order = Order(
            id = generateOrderId(),
            sellerName = sellerName,
            status = "待支付",
            productTitle = productTitle,
            productPrice = productPrice,
            totalPrice = productPrice,
            quantity = "x $quantity",
            tag1 = tag1,
            tag2 = tag2,
            action1Text = "取消订单",
            action2Text = "立即支付",
            productImageUrl = productImageUrl
        )
        
        orders.add(0, order) // 添加到列表开头
        return order
    }
    
    /**
     * 获取所有订单
     */
    fun getAllOrders(): List<Order> = orders.toList()
    
    /**
     * 根据状态获取订单
     */
    fun getOrdersByStatus(status: String): List<Order> {
        return orders.filter { it.status == status }
    }
    
    /**
     * 更新订单状态
     */
    fun updateOrderStatus(orderId: String, newStatus: String) {
        val order = orders.find { it.id == orderId }
        order?.let {
            val index = orders.indexOf(it)
            val updatedOrder = it.copy(
                status = newStatus,
                action1Text = when (newStatus) {
                    "待支付" -> "取消订单"
                    "待发货" -> "申请退款"
                    "已发货" -> "申请退款"
                    "交易成功" -> "删除订单"
                    else -> "删除订单"
                },
                action2Text = when (newStatus) {
                    "待支付" -> "立即支付"
                    "待发货" -> "提醒发货"
                    "已发货" -> "确认收货"
                    "交易成功" -> "申请售后"
                    else -> "申请售后"
                }
            )
            orders[index] = updatedOrder
        }
    }
    
    /**
     * 删除订单
     */
    fun deleteOrder(orderId: String): Boolean {
        val order = orders.find { it.id == orderId }
        return order?.let {
            orders.remove(it)
            true
        } ?: false
    }
    
    /**
     * 生成订单ID
     */
    private fun generateOrderId(): String {
        return "ORDER_${System.currentTimeMillis()}_${Random().nextInt(1000)}"
    }
    
    /**
     * 清空所有订单（用于测试）
     */
    fun clearAllOrders() {
        orders.clear()
    }
} 